//
//  LSHttpTool.m
//  LookScore
//
//  Created by wr on 2018/1/16.
//  Copyright © 2018年 ChongQingXunTiCompany. All rights reserved.
//

#import "LSHttpTool.h"
#import <AFNetworking.h>
#import <MJExtension.h>
#import <AFNetworkActivityIndicatorManager.h>
//#import "LSHttpParameter.h"
#import "LSAccountArchive.h"
static const NSUInteger REQUEST_TIME = 30;


@implementation LSHttpTool


/**
 组装基础参数
 @param parameters 业务参数
 @return 组合值
 */
+(NSDictionary *)installGetRequestParameters:(NSDictionary *)parameters{
    //组合参数
    NSMutableDictionary *parms = [NSMutableDictionary dictionary];
    
    //客户端类型
    parms[@"c"] = @3;//0 web 1 wap 2 andriod 3 ios
    
    //客户端包名字
    parms[@"p"] = @"main";//主包
    
    //当前的时间戳
    parms[@"t"] =[CommonClass readStampTimeString];
    
    //客户端Token
    parms[@"tk"] = [LSAccountArchive objectUserToken];
    
    //客户端版本 取出当前软件版本从Info.plist中获得
    parms[@"v"] = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    
    [parms addEntriesFromDictionary:parameters];
    
    NSMutableDictionary * parametersDic = @{}.mutableCopy;
    for (NSString * key in parms.allKeys) {
        NSString * value = parms[key];
        [parametersDic setObject:value forKey:[key lowercaseString]];
    }
    NSString * parametesStr = [[CommonClass stringFromParameters:parametersDic] stringByRemovingPercentEncoding];
    
    //业务参数和之前的 客户端加密
    parms[@"s"] = [CommonClass MD5:parametesStr];
    
    return parms;
}

/**
 组装基础参数
 @param parameters 业务参数
 @return 组合值
 */
+(NSDictionary *)installPostRequestParameters:(NSDictionary *)parameters{
    
    //组合参数
    NSMutableDictionary *parms = [NSMutableDictionary dictionary];
    
    //客户端类型
    parms[@"c"] = @3;//0 web 1 wap 2 andriod 3 ios
    
    //客户端包名字
    parms[@"p"] = @"main";//主包
    
    //当前的时间戳
    parms[@"t"] =[CommonClass readStampTimeString];
    
    //客户端Token
    parms[@"tk"] = [LSAccountArchive objectUserToken];
   
    //客户端版本 取出当前软件版本从Info.plist中获得
    parms[@"v"] = [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    
    NSMutableDictionary *dict=[NSMutableDictionary dictionaryWithDictionary:parms.copy];
    
    [dict addEntriesFromDictionary:parameters];
    
    NSMutableDictionary * parametersDic = @{}.mutableCopy;
    
    //将字典的大写key转出小写
    for (NSString * key in dict.allKeys) {
        NSString * value = dict[key];
        [parametersDic setObject:value forKey:[key lowercaseString]];
    }
    
    NSString *allSString=[[CommonClass stringFromParameters:parametersDic] stringByRemovingPercentEncoding];
    
    //客户端加密
    parms[@"s"] = [CommonClass MD5:allSString];

    return parms;
}

+ (void)GET:(NSString *)URLString parameters:(id)parameters success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure
{
   
    // 创建请求管理者
    AFHTTPSessionManager *Manager = [AFHTTPSessionManager manager];

    [Manager.requestSerializer setTimeoutInterval:REQUEST_TIME]; //设置请求的超时时间
    
    Manager.responseSerializer = [AFJSONResponseSerializer serializer]; //设置服务器返回结果的类型:JSON
    
//    Manager.requestSerializer=[AFJSONRequestSerializer serializer];//设置服务器请求类型:JSON
    
    Manager.operationQueue.maxConcurrentOperationCount = 5; //请求队列的最大并发数
    
    Manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    KWeakSelf(self);
    NSDictionary *parm=[weakself installGetRequestParameters:parameters];


//    NSString *urlRealString=[NSString stringWithFormat:@"%@/api/%@",@"http://101.132.148.59:304",URLString];
//    NSString *urlRealString=[NSString stringWithFormat:@"%@/api/%@",@"http://192.168.0.123:622",URLString];//猪猪

    NSString *urlRealString=[NSString stringWithFormat:@"%@/api/%@",LSHostURL,URLString];


    [Manager GET:urlRealString parameters:parm progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
      success ? success(responseObject) :nil;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
    
  
}

//15223290883  @Qwe123

+ (void)Post:(NSString *)URLString  parameters:(id)parameters success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure
{
    // 创建请求管理者
    AFHTTPSessionManager *Manager = [AFHTTPSessionManager manager];
    
    [Manager.requestSerializer setTimeoutInterval:REQUEST_TIME]; //设置请求的超时时间
    
    Manager.responseSerializer = [AFJSONResponseSerializer serializer]; //设置服务器返回结果的类型:JSON
    
    //    Manager.requestSerializer=[AFJSONRequestSerializer serializer];//设置服务器请求类型:JSON
    
    Manager.operationQueue.maxConcurrentOperationCount = 5; //请求队列的最大并发数
    
    Manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
    KWeakSelf(self);
    NSDictionary *parm=[weakself installPostRequestParameters:parameters];
    
//    [LSAccountArchive objectApiDomain]

//    NSString *urlRealString=[NSString stringWithFormat:@"%@/api/%@",@"http://101.132.148.59:304",URLString];
//    NSString *urlRealString=[NSString stringWithFormat:@"%@/api/%@",@"http://192.168.0.123:622",URLString];//猪猪

    NSString *urlRealString=[NSString stringWithFormat:@"%@/api/%@",LSHostURL,URLString];

    
    urlRealString=[NSString stringWithFormat:@"%@?%@",urlRealString,[CommonClass stringFromParameters:parm]];
    
    [Manager POST:urlRealString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
      
        success ? success(responseObject) :nil;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}

/**
 *  上传请求,支持批量上传, 各个MXUploadParam 装进uploadParamArray 里面传入
 *
 *  @param URLString  请求的基本的url
 *  @param parameters 请求的参数字典
 *  @param success    请求成功的回调
 *  @param failure    请求失败的回调
 */

+ (void)Upload:(NSString *)URLString parameters:(id)parameters uploadParamArray:(NSArray *)uploadParamArray success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure{

    // 创建请求管理者
    AFHTTPSessionManager *Manager = [AFHTTPSessionManager manager];
    
    [Manager.requestSerializer setTimeoutInterval:REQUEST_TIME]; //设置请求的超时时间
    
    Manager.responseSerializer = [AFJSONResponseSerializer serializer]; //设置服务器返回结果的类型:JSON
    
    //    Manager.requestSerializer=[AFJSONRequestSerializer serializer];//设置服务器请求类型:JSON
    
    Manager.operationQueue.maxConcurrentOperationCount = 5; //请求队列的最大并发数
    
    Manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];

    NSDictionary *parm=[self installPostRequestParameters:parameters];
    


    NSString *urlRealString=[NSString stringWithFormat:@"%@/api/%@",LSHostURL,URLString];

    
    urlRealString=[NSString stringWithFormat:@"%@?%@",urlRealString,[CommonClass stringFromParameters:parm]];
    
    [Manager POST:urlRealString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        for(NSInteger i = 0; i < uploadParamArray.count; i++)
        {
            NSData *data = [self compressOriginalImage:uploadParamArray[i] toMaxDataSizeKBytes:300];
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            //            formatter.dateFormat = @"yyyyMMddHHmmss";
            [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
            
            NSString *imageName = [formatter stringFromDate:[NSDate date]];
            
            // 上传的参数名，在服务器端保存文件的文件夹名
            NSString * Name = [NSString stringWithFormat:@"%@%ld", imageName,i+1];
            // 上传filename
            NSString * fileName = [NSString stringWithFormat:@"%@.jpeg", Name];
            
            [formData appendPartWithFileData:data name:@"file" fileName:fileName mimeType:@"image/jpeg"];
        }
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success ? success(responseObject) :nil;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
   
}

/**
 *  压缩图片到指定文件大小
 *
 *  @param image 目标图片
 *  @param size  目标大小（最大值）
 *
 *  @return 返回的图片文件
 */
+ (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{
    NSData * data = UIImageJPEGRepresentation(image, 1.0);
    CGFloat dataKBytes = data.length/1000.0;
    CGFloat maxQuality = 0.9f;
    CGFloat lastData = dataKBytes;
    while (dataKBytes > size && maxQuality > 0.01f) {
        maxQuality = maxQuality - 0.01f;
        data = UIImageJPEGRepresentation(image, maxQuality);
        dataKBytes = data.length / 1000.0;
        if (lastData == dataKBytes) {
            break;
        }else{
            lastData = dataKBytes;
        }
    }
    return data;
}

#pragma mark -- 不拼接  不加密的网络请求

+ (void)GETNormarData:(NSString *)URLString parameters:(id)parameters success:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure
{
    
    // 创建请求管理者
    AFHTTPSessionManager *Manager = [AFHTTPSessionManager manager];
    
    [Manager.requestSerializer setTimeoutInterval:REQUEST_TIME]; //设置请求的超时时间
    
    Manager.responseSerializer = [AFJSONResponseSerializer serializer]; //设置服务器返回结果的类型:JSON
    
    //    Manager.requestSerializer=[AFJSONRequestSerializer serializer];//设置服务器请求类型:JSON
    
    Manager.operationQueue.maxConcurrentOperationCount = 5; //请求队列的最大并发数
    
    Manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/plain", nil];
//    KWeakSelf(self);
//    NSDictionary *parm=[weakself installGetRequestParameters:parameters];
    
    
    //    NSString *urlRealString=[NSString stringWithFormat:@"%@/api/%@",@"http://101.132.148.59:304",URLString];
    //    NSString *urlRealString=[NSString stringWithFormat:@"%@/api/%@",@"http://192.168.0.123:622",URLString];//猪猪
    
//    NSString *urlRealString=[NSString stringWithFormat:@"%@/api/%@",LSHostURL,URLString];
    
    
    [Manager GET:URLString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        success ? success(responseObject) :nil;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
    
    
}
@end
